define([
    'app',
    'js/api/OrderAPI',
    'js/api/ProductAPI'
    ], function (app) {
    'use strict';
    app.controller('productCtrl', ['$scope','$rootScope', '$http', '$stateParams', '$location', 'OrderAPI', 'ProductAPI', function($scope, $rootScope, $http, $stateParams, $location, OrderAPI, ProductAPI) {

        
        $scope.content = true;
        $scope.size = false;
        $scope.moveToContent = function () {
            $scope.content = true;
            $scope.size = false;
            mySwiper1.slideTo(0);
        }

        $scope.moveToSize = function () {
            $scope.content = false;
            $scope.size = true;
            mySwiper1.slideTo(1);
        }

        var mySwiper = new Swiper('.content-info', {

        });

        var mySwiper1 = new Swiper('.product-tab', {
            noSwipingClass: 'swiper-no-swiping',
        });


        function getProductdata() {
            var name = $stateParams.name;
            console.log(name);  
            ProductAPI.dataUrl(name).then(function(data) {
                console.log(data);   
                if(data.model.objData.panels.size) {
                    $scope.needRingSize = true;   
                    $scope.ringSizeData = data.model.objData.panels.size.options.ringSize.data;

                }  
                var cdn = 'http://cdn.m-lab.cn/';
                for (var i in data.images) {
                    if (data.images[i]['main']) {
                        $scope.mainImg = cdn + data.images[i]['main'];
                        break;
                    }
                }
                function initOrderObj(options, thirdparty){
                    var getPrice = eval(data.priceCount.js);
                    var price = getPrice(options) * 100;
                    var orderObj = {
                        platform: {
                            name: thirdparty
                        },
                        subject: '马良行-第三方订单',
                        body: thirdparty,
                        allSubTotal: price,
                        allQuantity: 1,
                        allDiscountAmount: 0,
                        allShippingCost: 0,
                        allTotal: price,
                        change: 0,
                        item: [],
                        message: $scope.phone.input || thirdpartyOrderId,
                        note: thirdparty + '订单',
                        address: {
                            name: '许鹏飞',
                            phone: '15900836787',
                            province: {
                                objectId: '26',
                                __type: 'Pointer',
                                className: 'Address_province'
                            },
                            city: {
                                objectId: '382',
                                __type: 'Pointer',
                                className: 'Address_city'
                            },
                            detail: thirdparty + '订单无地址'
                        }
                    };

                    orderObj.item.push({
                        product: {
                            __type: 'Pointer',
                            className: 'Product',
                            objectId: data.objectId
                        },
                        options: options,
                        price: price,
                        priceDiscount: price,
                        subTotal: price,
                        total: price,
                        quantity: 1,
                        shippingCost: 0
                    });
                    return orderObj;
                }
                $scope.confirm = function(){
                    if($scope.submitting) return;
                    if(!$scope.wavUrl) {
                        alert('请先录制语音');
                        return;
                    }
                    if($scope.needRingSize && !$scope.ringSize){
                        alert('请选择戒围');
                        return;
                    }
                    $scope.submitting = true;
                    $scope.confirmBtn = '提交中';
                    var orderObj = initOrderObj({
                        className : data.model.objData.object,
                        materialName: 'silver',
                        heights: $scope.heights,
                        wavUrl: $scope.wavUrl,
                        ringSize: $scope.ringSize,
                        type: $scope.type
                    }, thirdparty);


                    OrderAPI.anonymousOrder(orderObj).then(function(data) {
                        
                        
                        alert('录音成功，无需重复提交');
                        if(redirectUri) {
                            $scope.confirmBtn = '下单成功';
                            location.href = redirectUri.slice(0, 4) == 'http' ? redirectUri : 'http://' + redirectUri;
                        } else {
                            location.reload();
                        }

                    }, function(error) {
                        console.log('下单失败:', error);
                        alert('录音失败，请重新录制')
                        $scope.submitting = false;
                        $scope.confirmBtn = '确定';
                    });
                }



            });
        }
        getProductdata();


        var thirdpartyName = {
        	'yangqi' : '氧气',
        	'xmly' : '喜马拉雅',
        	'liangcang' : '良仓',
            'hofo' : 'hofo',
            'touch': '触宝',
            'jianjiao': '尖叫',
            'shishi': '拾柿',
            'huishi': '惠氏'
        };
        var thirdpartyOrderId = $location.search().order_id || 'null';
        var redirectUri = $location.search().redirect_uri;
        var thirdpartyId = $location.search().thirdparty_id || $location.search().from || 'liangcang';
        var thirdparty = thirdpartyName[thirdpartyId] || '';
        $scope.type = $location.search().type;

        function validatemobile(mobile) {
           if(mobile.length==0) 
           { 
              alert('请输入手机号码！'); 
              return false; 
           }     
           if(mobile.length!=11) 
           { 
               alert('请输入有效的手机号码！'); 
               return false; 
           } 
            
           var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/; 
           if(!myreg.test(mobile)) 
           { 
               alert('请输入有效的手机号码！'); 
               return false; 
           } 
           return true;
        } 

        function closePhoneDialog(){
            var step1 = document.getElementById('step1');
            var step3 = document.getElementById('step3');
            step1.style.opacity = 1;
            step3.style.display = 'none';
        }
        $scope.showCarve = true;
        if(thirdpartyId == 'liangcang' || thirdpartyId == 'yangqi') {
            $scope.showCarve = false;
            closePhoneDialog();
        }
        $scope.phone = {};
        $scope.phone.input = '';
        $scope.getPhone = function () {
            if(validatemobile($scope.phone.input)) {

                closePhoneDialog();
            }
                //closePhoneDialog();
        }




        


        $scope.submitting = false;
        $scope.confirmBtn = '确定';
        


        function drawWaveform(waveHeights, options) {
            var x = options.x;
            var y = options.y;
            var w = options.w;
            var h = options.h;
            var maxHeight = -1000;
            for (var i = 0; i < waveHeights.length; i++) {
                maxHeight = maxHeight > waveHeights[i] ? maxHeight : waveHeights[i];
            }
            var canvas = document.getElementById("carve");
            if (canvas) {
                var ctx = canvas.getContext("2d");
                ctx.lineWidth = 2;
                ctx.strokeStyle = 'rgba(180,180,180,1)';
                ctx.shadowOffsetX = 0.7; // 阴影Y轴偏移
                ctx.shadowOffsetY = 0.7; // 阴影X轴偏移
                ctx.shadowBlur = 0.5; // 模糊尺寸
                ctx.shadowColor = 'rgba(255, 255, 255, 1)'; // 颜色


                ctx.clearRect(0, 0, 1000, 1000);
                ctx.beginPath();
                ctx.moveTo(x, y);
                var count = waveHeights.length;
                var scale = h / (maxHeight);
                var step = w / (count + 1);
                for (var i = 0; i < waveHeights.length; i++) {
                    ctx.lineTo((i) * step + x, y + scale * (waveHeights[i]));

                }
                ctx.stroke();


            }
        }

        if($rootScope.waveformEvent1) $rootScope.waveformEvent1();
        $rootScope.waveformEvent1 = $rootScope.$on('waveform', function(event, waveHeights, data, wavUrl, localId, warning){
            $scope.heights = data;
            $scope.wavUrl = wavUrl;
           	drawWaveform(waveHeights, {x: 0, y: 40, w: 240, h: 40*0.3});

            
        });






    }])
});
